package com.argrace.smart.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.text.TextPaint;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.alink.business.alink.ALinkBusinessEx;
import com.aliyun.alink.sdk.net.anet.api.AError;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryRequest;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryResponse;
import com.argrace.smart.R;
import com.argrace.smart.base.BaseActivity;
import com.argrace.smart.base.ConstantConfigure;
import com.argrace.smart.entity.AirConditionEntity;
import com.argrace.smart.entity.Key_ValueEntity;
import com.argrace.smart.entity.MineZigBeeDeviceListEntity;
import com.argrace.smart.model.LocalDb_QingJing_DeviceTable;
import com.argrace.smart.ui.AirConditionView;
import com.argrace.smart.util.AlinkHttpUtil;
import com.argrace.smart.util.Logg;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by argrace_dev_1 on 2018/2/24.
 */

public class DeviceControl_AirConditionActivity extends BaseActivity {
    private ImageView img;
    MineZigBeeDeviceListEntity bean;
    private LinearLayout container;
    private ArrayList<AirConditionView> views = new ArrayList<>();
    private int type = ConstantConfigure.TYPE_CONTROL;
    private String name;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_devicecontrol_aircond);
        init();
    }

    private void init() {
        bean = (MineZigBeeDeviceListEntity) getIntent().getSerializableExtra("deviceinfo");
        name = getIntent().getStringExtra("name");
        type = getIntent().getIntExtra("type", ConstantConfigure.TYPE_CONTROL);
        Logg.i("info", "设备详情的uuid是" + bean.getUuid());
        setView();
        setTitle(true, false, bean.getName());
        showRight(true, R.mipmap.icon_modify);


        if (type == ConstantConfigure.TYPE_SETTING) {
            //进入设备修改保存状态界面
            showRight(true, R.mipmap.head_title_tick);
            setLeftandRightClickListeners(null, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showDialog_KongTiao(bean);

                }
            });
        } else {
            showRight(true, R.mipmap.icon_modify);
            //进入设备修改界面
            setLeftandRightClickListeners(null, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(DeviceControl_AirConditionActivity.this, DeviceModifyActivity.class);
                    intent.putExtra("uuid", bean.getUuid());
                    intent.putExtra("model", bean.getModel());
                    startActivity(intent);
                }
            });
        }


        getDeviceDetailInfo();
    }

    private void setView() {
        img = (ImageView) findViewById(R.id.activity_devicecontrol_img);
        container = (LinearLayout) findViewById(R.id.activity_devicecontrol_aircond_container);
        img.setImageResource(R.mipmap.bg_aircondition);
    }

    //查询设备最新状态
    private void getDeviceDetailInfo() {
        String method = "mtop.openalink.app.core.device.get.status";
        HashMap<String, Object> params = new HashMap<>();
        params.put("uuid", bean.getUuid());
        AlinkHttpUtil.AlinkHttpRequest(method, params, new ALinkBusinessEx.IListener() {
            @Override
            public void onSuccess(TransitoryRequest transitoryRequest, TransitoryResponse transitoryResponse) {
                if (transitoryResponse == null || transitoryResponse.data == null) {
                    return;
                }
                Log.i("info", "子设备最新状态成功" + transitoryResponse.data);
                JSONObject obj = JSON.parseObject(transitoryResponse.data.toString());
                fillData(obj, obj.getString("uuid"));
            }

            @Override
            public void onFailed(TransitoryRequest transitoryRequest, AError aError) {
                Log.i("info", "子设备最新状态失败" + aError.getMsg() + aError.getCode());
            }
        });
    }

    private void fillData(JSONObject obj, String uuid) {
        if (uuid == null || !uuid.equals(bean.getUuid())) {
            return;
        }
        AirConditionEntity entity = JSONObject.parseObject(obj.toString(), AirConditionEntity.class);
        if (bean.getModel().equals(ConstantConfigure.MODEL_KONGTIAOZHUANHUANQI) && entity != null) {
            if (entity.getChannelCount() != null && entity.getChannelCount().getValue() != null) {
                int airsNum = Integer.parseInt(entity.getChannelCount().getValue());
                for (int i = 0; i < airsNum; i++) {
                    AirConditionView ariView;
                    if (type == ConstantConfigure.TYPE_SETTING) {
                        ariView = new AirConditionView(this, bean.getUuid(), false);
                    } else {
                        ariView = new AirConditionView(this, bean.getUuid(), true);
                    }
                    //+1使得position与sds平台的后缀相同
                    ariView.setPosition(i + 1);
                    container.addView(ariView);
                    views.add(ariView);
                }
            }
            fillDataAfterReciever(entity);
        }
    }

    private void fillDataAfterReciever(AirConditionEntity entity) {
        //根据entity更新界面数据,当前温度为-22到55，设定温度为16-32，开关0关闭1开启，模式1制冷2制热3送风4除湿，风俗2低3中4高
        //第一条空调数据
        Key_ValueEntity currentTemperature_1 = entity.getCurrentTemperature_1();
        Key_ValueEntity targetTemperature_1 = entity.getTargetTemperature_1();
        Key_ValueEntity switch_1 = entity.getSwitch_1();
        Key_ValueEntity workModel_1 = entity.getWorkMode_1();
        Key_ValueEntity windSpeed_1 = entity.getWindSpeed_1();
        if (currentTemperature_1 != null || targetTemperature_1 != null || switch_1 != null || workModel_1 != null || windSpeed_1 != null) {
            fillAirView(currentTemperature_1, targetTemperature_1, switch_1, workModel_1, windSpeed_1, views.get(0));
        }
        //第二条空调数据
        Key_ValueEntity currentTemperature_2 = entity.getCurrentTemperature_2();
        Key_ValueEntity targetTemperature_2 = entity.getTargetTemperature_2();
        Key_ValueEntity switch_2 = entity.getSwitch_2();
        Key_ValueEntity workModel_2 = entity.getWorkMode_2();
        Key_ValueEntity windSpeed_2 = entity.getWindSpeed_2();
        if (currentTemperature_2 != null || targetTemperature_2 != null || switch_2 != null || workModel_2 != null || windSpeed_2 != null) {
            fillAirView(currentTemperature_2, targetTemperature_2, switch_2, workModel_2, windSpeed_2, views.get(1));
        }
        //第三条空调数据
        Key_ValueEntity currentTemperature_3 = entity.getCurrentTemperature_3();
        Key_ValueEntity targetTemperature_3 = entity.getTargetTemperature_3();
        Key_ValueEntity switch_3 = entity.getSwitch_3();
        Key_ValueEntity workModel_3 = entity.getWorkMode_3();
        Key_ValueEntity windSpeed_3 = entity.getWindSpeed_3();
        if (currentTemperature_3 != null || targetTemperature_3 != null || switch_3 != null || workModel_3 != null || windSpeed_3 != null) {
            fillAirView(currentTemperature_3, targetTemperature_3, switch_3, workModel_3, windSpeed_3, views.get(2));
        }
        //第四条空调数据
        Key_ValueEntity currentTemperature_4 = entity.getCurrentTemperature_4();
        Key_ValueEntity targetTemperature_4 = entity.getTargetTemperature_4();
        Key_ValueEntity switch_4 = entity.getSwitch_4();
        Key_ValueEntity workModel_4 = entity.getWorkMode_4();
        Key_ValueEntity windSpeed_4 = entity.getWindSpeed_4();
        if (currentTemperature_4 != null || targetTemperature_4 != null || switch_4 != null || workModel_4 != null || windSpeed_4 != null) {
            fillAirView(currentTemperature_4, targetTemperature_4, switch_4, workModel_4, windSpeed_4, views.get(3));
        }
        //第五条空调数据
        Key_ValueEntity currentTemperature_5 = entity.getCurrentTemperature_5();
        Key_ValueEntity targetTemperature_5 = entity.getTargetTemperature_5();
        Key_ValueEntity switch_5 = entity.getSwitch_5();
        Key_ValueEntity workModel_5 = entity.getWorkMode_5();
        Key_ValueEntity windSpeed_5 = entity.getWindSpeed_5();
        if (currentTemperature_5 != null || targetTemperature_5 != null || switch_5 != null || workModel_5 != null || windSpeed_5 != null) {
            fillAirView(currentTemperature_5, targetTemperature_5, switch_5, workModel_5, windSpeed_5, views.get(4));
        }
        //第六条空调数据
        Key_ValueEntity currentTemperature_6 = entity.getCurrentTemperature_6();
        Key_ValueEntity targetTemperature_6 = entity.getTargetTemperature_6();
        Key_ValueEntity switch_6 = entity.getSwitch_6();
        Key_ValueEntity workModel_6 = entity.getWorkMode_6();
        Key_ValueEntity windSpeed_6 = entity.getWindSpeed_6();
        if (currentTemperature_6 != null || targetTemperature_6 != null || switch_6 != null || workModel_6 != null || windSpeed_6 != null) {
            fillAirView(currentTemperature_6, targetTemperature_6, switch_6, workModel_6, windSpeed_6, views.get(5));
        }
    }

    @Override
    protected void dorecieve(JSONObject obj) {
        super.dorecieve(obj);
        if (obj == null || obj.getJSONObject("params") == null || obj.getJSONObject("params").getJSONObject("data") == null || obj.getJSONObject("params").getString("uuid") == null) {
            return;
        }
        AirConditionEntity entity = JSONObject.parseObject(obj.getJSONObject("params").getJSONObject("data").toString(), AirConditionEntity.class);
        fillDataAfterReciever(entity);
    }

    private void fillAirView(Key_ValueEntity currentTemperature, Key_ValueEntity targetTemperature, Key_ValueEntity switch_state, Key_ValueEntity workModel, Key_ValueEntity windSpeed, AirConditionView view) {
        if (currentTemperature != null && currentTemperature.getValue() != null) {
            view.getCurrentTemperature().setText((int) Float.parseFloat(currentTemperature.getValue()) + "℃");
        }
        if (targetTemperature != null && targetTemperature.getValue() != null) {
            view.getTagTemperature().setText((int) Float.parseFloat(targetTemperature.getValue()) + "℃");
        }
        if (switch_state != null && switch_state.getValue() != null) {
            if (switch_state.getValue().equals("0")) {
                view.getDrawableSwitch().setSwitchOn(false);
            } else {
                view.getDrawableSwitch().setSwitchOn(true);
            }
            view.getDrawableSwitch().invalidate();
        }

        if (workModel != null && workModel.getValue() != null) {
            view.setModel(workModel.getValue());
        }
        if (windSpeed != null && windSpeed.getValue() != null) {
            view.setWind(windSpeed.getValue());
        }
    }

    private void showDialog_KongTiao(final MineZigBeeDeviceListEntity bean) {
        final AlertDialog alertDialog = new AlertDialog.Builder(
                this).create();
        alertDialog.setCanceledOnTouchOutside(true);
        alertDialog.show();
        Window window = alertDialog.getWindow();
        window.setContentView(R.layout.dialog_changjingkaiguan);
        TextView text1 = (TextView) window
                .findViewById(R.id.dialog_changjingkaiguan_text1);
        TextView text2 = (TextView) window
                .findViewById(R.id.dialog_changjingkaiguan_text2);
        TextView text3 = (TextView) window
                .findViewById(R.id.dialog_changjingkaiguan_text3);
        TextView text4 = (TextView) window
                .findViewById(R.id.dialog_changjingkaiguan_text4);
        TextView text5 = (TextView) window
                .findViewById(R.id.dialog_changjingkaiguan_text5);
        TextView text6 = (TextView) window
                .findViewById(R.id.dialog_changjingkaiguan_text6);
        text1.setText("空调一");
        TextPaint tp1 = text1.getPaint();
        tp1.setFakeBoldText(true);
        text2.setText("空调二");
        TextPaint tp2 = text2.getPaint();
        tp2.setFakeBoldText(true);
        text3.setText("空调三");
        TextPaint tp3 = text3.getPaint();
        tp3.setFakeBoldText(true);
        text4.setText("空调四");
        TextPaint tp4 = text4.getPaint();
        tp4.setFakeBoldText(true);
        text5.setText("空调五");
        TextPaint tp5 = text5.getPaint();
        tp5.setFakeBoldText(true);
        text6.setText("空调六");
        TextPaint tp6 = text6.getPaint();
        tp6.setFakeBoldText(true);
        text1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                LocalDb_QingJing_DeviceTable entity = new LocalDb_QingJing_DeviceTable();
                entity.setJson_params(views.get(0).translateParams());
                entity.updateAll("uuid = ? and LocalDb_DeviceTable_deviceId = ?", bean.getUuid(), name);
                finish();
            }
        });
        text2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                LocalDb_QingJing_DeviceTable entity = new LocalDb_QingJing_DeviceTable();
                entity.setJson_params(views.get(1).translateParams());
                entity.updateAll("uuid = ? and LocalDb_DeviceTable_deviceId = ?", bean.getUuid(), name);
                finish();
            }
        });
        text3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                LocalDb_QingJing_DeviceTable entity = new LocalDb_QingJing_DeviceTable();
                entity.setJson_params(views.get(2).translateParams());
                entity.updateAll("uuid = ? and LocalDb_DeviceTable_deviceId = ?", bean.getUuid(), name);
                finish();
            }
        });
        text4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                LocalDb_QingJing_DeviceTable entity = new LocalDb_QingJing_DeviceTable();
                entity.setJson_params(views.get(3).translateParams());
                entity.updateAll("uuid = ? and LocalDb_DeviceTable_deviceId = ?", bean.getUuid(), name);
                finish();
            }
        });
        text5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                LocalDb_QingJing_DeviceTable entity = new LocalDb_QingJing_DeviceTable();
                entity.setJson_params(views.get(4).translateParams());
                entity.updateAll("uuid = ? and LocalDb_DeviceTable_deviceId = ?", bean.getUuid(), name);
                finish();
            }
        });
        text6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                LocalDb_QingJing_DeviceTable entity = new LocalDb_QingJing_DeviceTable();
                entity.setJson_params(views.get(5).translateParams());
                entity.updateAll("uuid = ? and LocalDb_DeviceTable_deviceId = ?", bean.getUuid(), name);
                finish();
            }
        });

    }
}
